package day06.handler;

import day06.packet.LoginRequestPacket;
import day06.packet.Packet;
import day06.packet.LoginResponsePacket;
import day06.util.PacketCodeC;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author chenshijie
 * @date 2023/12/23 15:34
 */
//@ChannelHandler.Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {

    private final String USERNAME = "yu";
    private final String PASSWORD = "password";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        Packet packet = PacketCodeC.INSTANCE.decode((ByteBuf) msg);
        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        loginResponsePacket.setVersion(packet.getVersion());
        if (packet instanceof LoginRequestPacket) {
            LoginRequestPacket loginRequestPacket = (LoginRequestPacket) packet;

            // 登录校验
            if (valid(loginRequestPacket)) {
                // 成功
                System.out.println("校验成功");
                loginResponsePacket.setStatus(200);
                loginResponsePacket.setMsg("登录成功");

            } else {
                // 错误
                System.out.println("校验失败");
                loginResponsePacket.setStatus(405);
                loginResponsePacket.setMsg("密码错误或者账号不存在");
            }
        } else {
            System.out.println("查无此数据类型");
        }

        // 编码
        ByteBuf byteBuf = PacketCodeC.INSTANCE.encode(ctx.alloc(), loginResponsePacket);
        ctx.channel().writeAndFlush(byteBuf);
    }

    private boolean valid(LoginRequestPacket loginRequestPacket) {
        return USERNAME.equals(loginRequestPacket.getUsername()) && PASSWORD.equals(loginRequestPacket.getPassword());
    }
}
